import { Typography } from "@/pages/OrderModule/common/components/Typography";
import { useFetch } from "@/pages/OrderModule/common/hooks/useFetch";
import { Checkbox, Col, Radio, Row, Spin, message } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import ShopIcons from "@/views/components/ShopIcons";
import { queryShopList, queryQimenShopList } from "./server";

function dfs(node, cb) {
	if (!node) return;

	cb(node);
	if (node.items) {
		node.items.forEach(item => {
			dfs(item, cb);
		});
	}
}

function convertListToTree(list) {
	const tree = {};

	list.forEach(item => {
		const type = item.type;
		if (!tree[type]) {
			tree[type] = {
				name: item.typeName,
				type,
				items: []
			};
		}

		tree[type].items.push(item);
	});

	return tree;
}

export const MultipleSelectShop = props => {
	const { valueKey = "id", storeName, multiple, extraQuery = {}, onChange, onInit, value, checkAuthTime } = props;

	const queryType = extraQuery.type || ''

	// 是否是奇门店铺
	const isQimenShop = queryType === 13
	
	const { loading: shopListLoading, data: shopListResp, fetch: fetchShopList } = useFetch(isQimenShop ? queryQimenShopList : queryShopList, extraQuery, false);
	const [storeIds, setStoreIds] = useState(new Set(value || []));

	useEffect(() => {
		fetchShopList({ storeName })
			.then(res => {
			const list = res?.data?.records?.map(item=>({
				...item,
				storeName: item.systemStoreName || item.storeName
			}))
				onInit?.(list || []);
			})
			.finally(() => {
				setStoreIds(new Set(value || []));
				onChange?.(value || []);
			});
	}, [storeName]);

	useEffect(() => {
		setStoreIds(new Set(value));
	}, [value]);

	const shopTree = useMemo(() => {
		let listData = shopListResp?.data?.records;
		if (!listData) {
			return {};
		}
		
		return convertListToTree(listData);
	}, [shopListResp]);

	const Component = multiple ? Checkbox : Radio;

	function renderTitle(platform) {
		return (
			<div style={{ display: "flex", width: "100%", alignItems: "center" }}>
				<ShopIcons type={platform.type} />
				<Typography style={{ marginLeft: 8 }}>{platform.name}</Typography>
			</div>
		);
	}

	return (
		<div>
			<Spin spinning={shopListLoading}>
				{Object.values(shopTree).map((platform, index) => {
					const platformItems = [];
					dfs(platform, node => {
						if (node[valueKey]) {
							platformItems.push(node[valueKey]);
						}
					});
					const checkedItems = platformItems.filter(v => storeIds.has(v));
					const checkedNum = checkedItems.length;
					const checkAll = checkedNum === platformItems.length;
					const indeterminate = checkedNum > 0 && checkedNum < platformItems.length;

					return (
						<div style={{ marginTop: index ? 25 : 0 }} key={index}>
							{multiple ? (
								<Checkbox
									indeterminate={indeterminate}
									checked={checkAll}
									onChange={e => {
										const platformItemSet = new Set([...storeIds]);
										if (e.target.checked) {
											platformItems.forEach(v => platformItemSet.add(v));
										} else {
											platformItems.forEach(v => platformItemSet.delete(v));
										}
										const newData = [...platformItemSet];
										setStoreIds(new Set(newData));
										onChange?.(newData);
									}}
								>
									{renderTitle(platform)}
								</Checkbox>
							) : (
								renderTitle(platform)
							)}

							<Row style={{ marginLeft: 10 }}>
								{platform.items.map((item, index) => {
									return (
										<Col span={12} style={{ marginTop: 12 }} key={`${item[valueKey]}-${index}`}>
											<Component
												checked={storeIds.has(item[valueKey])}
												value={item[valueKey]}
												onChange={e => {
													if (checkAuthTime && ![0,-1].includes(item.type)) {
														if (!item.authExpireTime || Date.now() > item.authExpireTime * 1000) {
															return message.info("该店铺授权已过期或已失效，请重新勾选");
														}
													}
													if (multiple) {
														const platformItemSet = new Set([...storeIds]);
														if (e.target.checked) {
															platformItemSet.add(item[valueKey]);
														} else {
															platformItemSet.delete(item[valueKey]);
														}

														const newData = [...platformItemSet];
														setStoreIds(new Set(newData));
														onChange?.(newData);
														return;
													}
													const newData = [item[valueKey]];
													setStoreIds(new Set(newData));
													onChange?.(newData);
												}}
											>
												{item.systemStoreName || item.storeName}
											</Component>
										</Col>
									);
								})}
							</Row>
						</div>
					);
				})}
			</Spin>
		</div>
	);
};

export default MultipleSelectShop;
